import express from 'express';
import dotenv from 'dotenv'
import cors from 'cors';
import bodyParser from 'body-parser';
import delay from 'delay';

dotenv.config()

const app = express();

app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

import { ChatGPTAPIBrowser } from './chatgpt-api/src/'


async function say(api: any, ask: string) {

    const result = await api.sendMessage(ask)
    // console.log(result.response)
    // console.log(result.conversationId)
    // console.log(result.messageId)
    return [result.response, result.conversationId, result.messageId]
}

async function say_back(api: any, ask: string, cid: string, mid: string) {

    const result = await api.sendMessage(ask, {
        conversationId: cid,
        parentMessageId: mid
    })
    return [result.response, result.conversationId, result.messageId]
}


const email = process.env.OPENAI_EMAIL
const password = process.env.OPENAI_PASSWORD

const api = new ChatGPTAPIBrowser({
    email,
    password,
    debug: false,
    // minimize: true,
    // isGoogleLogin: true
})

api.initSession().then(() => {
    console.log('Init success.')
})

setInterval(() => {
    console.log('Timer refresh.')
    api.refreshSession()
}, 600000)

async function resetSession() {
    console.log('Refresh session..')
    await api.refreshSession()
}

app.post('/', (req, res) => {
    if (req.body.overdue) {
        delay(2000).then(() => {
            res.send({
                answer: "对话超时了，请刷新页面！",
                conversationId: 0,
                messageId: 0
            })
        })
    } else if (req.body.conversationId && req.body.messageId) {
        say_back(api, req.body.question, req.body.conversationId, req.body.messageId).then(([ans, cID, mID]) => {
            res.send({
                answer: ans,
                conversationId: cID,
                messageId: mID
            })
        }).catch((err) => {
            console.error(err)
            // process.exit(1)
            resetSession()
            delay(1000).then(() => {
                res.send({
                    answer: '愣神太久断线了，稍等10秒再试一下～',
                    // conversationId: 0,
                    // messageId: 0
                })
            })
        })
    } else {
        say(api, req.body.question).then(([ans, cID, mID]) => {
            res.send({
                answer: ans,
                conversationId: cID,
                messageId: mID
            })
        }).catch((err) => {
            console.error(err)
            // process.exit(1)
            resetSession()
            delay(1000).then(() => {
                res.send({
                    answer: '愣神太久断线了，再试一下～',
                    // conversationId: 0,
                    // messageId: 0
                })
            })
        })
    }
})

app.listen(3000, () => {
    console.log('The application is listening on port 3000!');
})
